#!/bin/bash

# 部署脚本
set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log() {
    echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] ✓${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] ⚠${NC} $1"
}

log_error() {
    echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ✗${NC} $1"
}

# 错误处理
handle_error() {
    log_error "$1"
    exit 1
}

# 检查Docker是否安装
check_docker() {
    if ! command -v docker &> /dev/null; then
        handle_error "Docker is not installed. Please install Docker first."
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        handle_error "Docker Compose is not installed. Please install Docker Compose first."
    fi
    
    log_success "Docker and Docker Compose are available"
}

# 创建必要的目录
create_directories() {
    log "Creating necessary directories..."
    mkdir -p data logs
    log_success "Directories created"
}

# 构建镜像
build_image() {
    log "Building Docker image..."
    docker-compose build --no-cache || handle_error "Failed to build Docker image"
    log_success "Docker image built successfully"
}

# 启动服务
start_services() {
    local mode=${1:-production}
    
    if [ "$mode" = "dev" ]; then
        log "Starting services in development mode..."
        docker-compose --profile dev up -d app-dev || handle_error "Failed to start development services"
        log_success "Development services started"
        log "Frontend: http://localhost:3000"
        log "Backend: http://localhost:8000"
    else
        log "Starting services in production mode..."
        docker-compose up -d app || handle_error "Failed to start production services"
        log_success "Production services started"
        log "Application: http://localhost:8000"
    fi
}

# 停止服务
stop_services() {
    log "Stopping services..."
    docker-compose down || handle_error "Failed to stop services"
    log_success "Services stopped"
}

# 查看日志
view_logs() {
    local service=${1:-app}
    log "Viewing logs for $service..."
    docker-compose logs -f $service
}

# 健康检查
health_check() {
    log "Performing health check..."
    
    # 等待服务启动
    sleep 10
    
    # 检查健康端点
    if curl -f http://localhost:8000/health > /dev/null 2>&1; then
        log_success "Health check passed"
        return 0
    else
        log_error "Health check failed"
        return 1
    fi
}

# 显示状态
show_status() {
    log "Service status:"
    docker-compose ps
}

# 清理
cleanup() {
    log "Cleaning up..."
    docker-compose down --volumes --remove-orphans
    docker system prune -f
    log_success "Cleanup completed"
}

# 备份数据
backup_data() {
    local backup_dir="backups/$(date +%Y%m%d_%H%M%S)"
    log "Creating backup in $backup_dir..."
    
    mkdir -p "$backup_dir"
    
    if [ -d "data" ]; then
        cp -r data "$backup_dir/"
        log_success "Data backed up to $backup_dir"
    else
        log_warning "No data directory found to backup"
    fi
}

# 恢复数据
restore_data() {
    local backup_path=$1
    
    if [ -z "$backup_path" ]; then
        log_error "Please specify backup path"
        exit 1
    fi
    
    if [ ! -d "$backup_path" ]; then
        log_error "Backup path does not exist: $backup_path"
        exit 1
    fi
    
    log "Restoring data from $backup_path..."
    
    # 停止服务
    stop_services
    
    # 备份当前数据
    if [ -d "data" ]; then
        mv data "data.backup.$(date +%Y%m%d_%H%M%S)"
    fi
    
    # 恢复数据
    cp -r "$backup_path/data" .
    
    log_success "Data restored from $backup_path"
}

# 显示帮助
show_help() {
    echo "Usage: $0 [COMMAND] [OPTIONS]"
    echo ""
    echo "Commands:"
    echo "  build                 Build Docker image"
    echo "  start [dev|prod]      Start services (default: prod)"
    echo "  stop                  Stop services"
    echo "  restart [dev|prod]    Restart services"
    echo "  logs [service]        View logs (default: app)"
    echo "  status                Show service status"
    echo "  health                Perform health check"
    echo "  backup                Backup data"
    echo "  restore <path>        Restore data from backup"
    echo "  cleanup               Clean up containers and images"
    echo "  help                  Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 start              Start in production mode"
    echo "  $0 start dev           Start in development mode"
    echo "  $0 logs app            View application logs"
    echo "  $0 restore backups/20231201_120000  Restore from backup"
}

# 主函数
main() {
    local command=${1:-help}
    
    case $command in
        "build")
            check_docker
            create_directories
            build_image
            ;;
        "start")
            check_docker
            create_directories
            start_services $2
            health_check
            ;;
        "stop")
            stop_services
            ;;
        "restart")
            stop_services
            start_services $2
            health_check
            ;;
        "logs")
            view_logs $2
            ;;
        "status")
            show_status
            ;;
        "health")
            health_check
            ;;
        "backup")
            backup_data
            ;;
        "restore")
            restore_data $2
            ;;
        "cleanup")
            cleanup
            ;;
        "help")
            show_help
            ;;
        *)
            log_error "Unknown command: $command"
            show_help
            exit 1
            ;;
    esac
}

# 运行主函数
main "$@"